//
//  SpecViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/8/25.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "SpecViewController.h"
#import "UIViewController+KNSemiModal.h"
#import "MallCommitOrdersViewController.h"

@interface SpecViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *photo;
@property (weak, nonatomic) IBOutlet UILabel *titleName;
@property (weak, nonatomic) IBOutlet UILabel *categoryName;
@property (weak, nonatomic) IBOutlet UILabel *specName;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UILabel *stock;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIButton *reduce;
@property (weak, nonatomic) IBOutlet UIButton *plus;
@property (weak, nonatomic) IBOutlet UILabel *quantity;
@property (weak, nonatomic) IBOutlet UIView *quantityView;



@property (strong, nonatomic)NSArray *skus;
@property (strong, nonatomic)NSArray *specs;	//(一共包含两个数组,下标0是分类，1是规格)

@property (strong, nonatomic)NSMutableArray *specBtnArr;
@property (strong, nonatomic)NSMutableArray *cateBtnArr;
@property NSInteger skuIndex;
@property NSInteger selectedCategoryIndex;
@property NSInteger selectedSpecIndex;
@property NSInteger tempStock;


@end

@implementation SpecViewController

- (void)viewWillAppear:(BOOL)animated
{
	self.titleName.text = self.model.title;
	self.categoryName.text = @"";
	self.specName.text = @"";
	if (self.skus.count) {
		NSArray *imageArr0 = [self.skus[0] valueForKey:@"photo"];
		if (imageArr0.count) {
			NSString *imageStr = imageArr0[0];
			NSURL *imageUrl = [NSURL URLWithString:imageStr];
			[self.photo sd_setImageWithURL:imageUrl placeholderImage:IMAGE(@"placeHolder")];
			NSLog(@"image : %@", imageStr);
		}
		NSString *priceStr = [self.skus[0] valueForKey:@"price"];
		//如果是拼单的话按照目前后台逻辑只显示唯一的拼单价
		if (self.type == 2 || self.type == 3) {
			priceStr = self.model.ecbuy_price;
		}
		NSString *stockStr = [self.skus[0] valueForKey:@"stock"];
		self.price.text = [NSString stringWithFormat:@"价格：￥%.2lf", [priceStr floatValue]/100];
		self.stock.text = [NSString stringWithFormat:@"库存：%@", stockStr];
		
	}
	if (self.specs.count) {
		self.categoryName.text = [NSString stringWithFormat:@"%@:", [self.specs[0] valueForKey:@"name"]];
		NSArray *cateArray = [self.specs[0] valueForKey:@"items"];
		
		//生成“型号”（或者说分类）的按钮数组
		int i = 0;
		CGFloat BtnX = self.categoryName.x+self.categoryName.width+20;	//下一个Btn的X坐标
		CGFloat BtnY = self.categoryName.y;	//下一个Btn的Y坐标
		for (NSDictionary *dict in cateArray)
		{
			CGSize btnSize = [LZCTools textSizeWithText:dict[@"val"] font:kUHSystemFontWithSize(13)];
			UIButton *cateBtn = [[UIButton alloc] initWithFrame:CGRectMake(BtnX, BtnY, btnSize.width+10, btnSize.height+3)];
			[cateBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
			if (cateBtn.x+cateBtn.width >= SCREEN_WIDTH) {
				cateBtn.frame = CGRectMake(self.categoryName.x+self.categoryName.width+20, BtnY+35, btnSize.width+10, btnSize.height+3);
				self.specName.frame = CGRectOffset(self.specName.frame, 0, 35);
				self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height+35);
			}
			//定位下一个button
			BtnX = cateBtn.x+cateBtn.width+10;
			BtnY = cateBtn.y;
			
			[cateBtn setTitle:dict[@"val"] forState:UIControlStateNormal];
			[cateBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
			[cateBtn setTitleColor:UIMainColorRGB forState:UIControlStateSelected];
			cateBtn.layer.borderWidth = 1.0;
			cateBtn.layer.borderColor = [kBlackColor CGColor];
			cateBtn.layer.cornerRadius = 5.0;
			[cateBtn setTitleEdgeInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
			cateBtn.tag = i;
			[cateBtn addTarget:self action:@selector(selectCate:) forControlEvents:UIControlEventTouchUpInside];
			[self.view addSubview:cateBtn];
			[self.cateBtnArr addObject:cateBtn];
			if (i == 0) {
				cateBtn.selected = YES;
				cateBtn.layer.borderColor = [UIMainColorRGB CGColor];
			}
			i++;
		}
		if (self.specs.count >= 2) {
			self.specName.text = [NSString stringWithFormat:@"%@:", [self.specs[1] valueForKey:@"name"]];
			NSArray *cateArray = [self.specs[1] valueForKey:@"items"];
			//生成“规格”的按钮
			int j = 0;
			CGFloat BtnX2 = self.specName.x+self.specName.width+20;
			CGFloat BtnY2 = self.specName.y;
			for (NSDictionary *dict in cateArray)
			{
				CGSize btnSize = [LZCTools textSizeWithText:dict[@"val"] font:kUHSystemFontWithSize(13)];
				UIButton *specBtn = [[UIButton alloc] initWithFrame:CGRectMake(BtnX2, BtnY2, btnSize.width+10, btnSize.height+3)];
				[specBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
				if (specBtn.x+specBtn.width >= SCREEN_WIDTH) {
					specBtn.frame = CGRectMake(self.specName.x+self.specName.width+20, BtnY2+35, btnSize.width+10, btnSize.height+3);
					self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height+35);
				}
				
				BtnX2 = specBtn.x+specBtn.width+10;
				BtnY2 = specBtn.y;
				[specBtn setTitle:dict[@"val"] forState:UIControlStateNormal];
				[specBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
				[specBtn setTitleColor:UIMainColorRGB forState:UIControlStateSelected];
				specBtn.layer.borderWidth = 1.0;
				specBtn.layer.cornerRadius = 5.0;
				specBtn.layer.borderColor = [kBlackColor CGColor];
				[specBtn setTitleEdgeInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
				specBtn.tag = 20+j;
				[specBtn addTarget:self action:@selector(selectSpec:) forControlEvents:UIControlEventTouchUpInside];
				[self.view addSubview:specBtn];
				[self.specBtnArr addObject:specBtn];
				if (j == 0) {
					specBtn.selected = YES;
					specBtn.layer.borderColor = [UIMainColorRGB CGColor];
				}
				j++;
			}
			
		}
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tempStock = [[self.skus[0] valueForKey:@"stock"] integerValue];
	
	[self.submitBtn setBackgroundColor:UIMainColorRGB];
	self.submitBtn.layer.cornerRadius = 5.0;
	[self.submitBtn addTarget:self action:@selector(clickSubmit:) forControlEvents:UIControlEventTouchUpInside];
	if (self.type == 0) {
		[self.submitBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
		
	}
	if (self.type == 1) {
		[self.submitBtn setTitle:@"立即购买" forState:UIControlStateNormal];
	}
	
	if (self.type == 2) {
		[self.submitBtn setTitle:@"开启拼单" forState:UIControlStateNormal];
	}
	if (self.type == 3) {
		[self.submitBtn setTitle:@"加入拼单" forState:UIControlStateNormal];
	}
	self.quantity.layer.borderWidth = 2;
	self.quantity.text = @"1";
	self.reduce.layer.borderWidth = 1;
	self.reduce.layer.cornerRadius = 5;
	self.plus.layer.borderWidth = 1;
	self.plus.layer.cornerRadius = 5;
    // Do any additional setup after loading the view from its nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setModel:(Goods *)model
{
	if (_model != model) {
		_model = model;
		_skus = model.skus;
		_specs = model.specs;
	}
}

- (NSMutableArray *)specBtnArr
{
	if (!_specBtnArr) {
		_specBtnArr = [[NSMutableArray alloc] init];
	}
	return _specBtnArr;
}

- (NSMutableArray *)cateBtnArr
{
	if (!_cateBtnArr) {
		_cateBtnArr = [[NSMutableArray alloc] init];
	}
	return _cateBtnArr;
}

- (void)selectCate:(UIButton *)sender
{
	sender.selected = YES;
	sender.layer.borderColor = [UIMainColorRGB CGColor];
	self.selectedCategoryIndex = sender.tag;
	[self calculateSkuIndex];
	for (UIButton *btn in self.cateBtnArr)
	{
		if (btn.tag != sender.tag) {
			btn.selected = NO;
			btn.layer.borderColor = [kBlackColor CGColor];
		}
	}
}

- (void)selectSpec:(UIButton *)sender
{
	sender.selected = YES;
	sender.layer.borderColor = [UIMainColorRGB CGColor];
    self.selectedSpecIndex = sender.tag-20;
	[self calculateSkuIndex];
	for (UIButton *btn in self.specBtnArr)
	{
		if (btn.tag != sender.tag) {
			btn.selected = NO;
			btn.layer.borderColor = [kBlackColor CGColor];
		}
	}
}

- (void)calculateSkuIndex
{
	for(int i = 0; i<self.skus.count; i++){
		NSString *skuStr = self.skus[i][@"name"];
		if (self.specs.count > 1) {
			NSString *categoryStr = self.specs[0][@"items"][self.selectedCategoryIndex][@"id"];
			NSString *specStr = self.specs[1][@"items"][self.selectedSpecIndex][@"id"];
			if ([skuStr isEqualToString:[categoryStr stringByAppendingString:[NSString stringWithFormat:@";%@", specStr]]] ||
				[skuStr isEqualToString:[specStr stringByAppendingString:[NSString stringWithFormat:@";%@", categoryStr]]]) {
				self.skuIndex = i;
			}
		}
		else {
			NSString *categoryStr = self.specs[0][@"items"][self.selectedCategoryIndex][@"id"];
			if ([skuStr isEqualToString:categoryStr]) {
				self.skuIndex = i;
			}
		}
	}
	//self.skuIndex = (self.selectedCategoryIndex+1)*(self.selectedSpecIndex+1)-1;
	if (self.skus.count) {
		NSArray *imageArr = [self.skus[self.skuIndex] valueForKey:@"photo"];
		if (imageArr.count) {
			NSString *imageStr = imageArr[0];
			NSURL *imageUrl = [NSURL URLWithString:imageStr];
			[self.photo sd_setImageWithURL:imageUrl placeholderImage:IMAGE(@"placeHolder")];
			NSLog(@"image : %@", imageStr);
		}
		NSString *priceStr = [self.skus[self.skuIndex] valueForKey:@"price"];
		NSString *stockStr = [self.skus[self.skuIndex] valueForKey:@"stock"];
		//如果是拼单的话按照目前后台逻辑只显示唯一的拼单价
		if (self.type == 2 || self.type == 3) {
			priceStr = self.model.ecbuy_price;
		}
        self.price.text = [NSString stringWithFormat:@"价格：￥%.2lf", [priceStr floatValue]/100];
		self.stock.text = [NSString stringWithFormat:@"库存：%@", stockStr];
        self.tempStock = [[self.skus[self.skuIndex] valueForKey:@"stock"] integerValue];
	}
}

- (void)clickSubmit:(UIButton *)sender
{
    if (self.tempStock >= 1) {
        if (self.type == 0) {
            NSDictionary *param = @{
                                    @"goods_id":[NSString stringWithFormat:@"%ld", self.goodId],
                                    @"quantity":self.quantity.text,
                                    @"sku":[self.skus[self.skuIndex] valueForKey:@"name"]
                                    };
            [[NetworkTool sharedTool] requestWithName:@"加入购物车" URLString:APIMallsCarts parameters:param method:@"PUT" callBack:^(id responseObject) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"加入购物车成功" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
                
            }];
        }
        if (self.type == 1 ) {
            NSDictionary *itemdic = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId],
                                      @"quantity":self.quantity.text,
                                      @"sku":[self.skus[self.skuIndex] valueForKey:@"name"]
                                      };
            NSArray *arr = @[itemdic];
            NSDictionary *param = @{@"items":arr};
            
            
            [[NetworkTool sharedTool] requestWithName:@"下单" URLString:APIMallsOrders parameters:param method:@"POST" callBack:^(id responseObject) {
                
                MallCommitOrdersViewController *commmitVC = [[MallCommitOrdersViewController alloc] init];
                //        commmitVC.order = responseObject[@"data"][0];
                
                commmitVC.orderData = responseObject[@"data"];
                NSLog(@"delegate is %@, nav is %@", self.delegate, self.delegate.navigationController);
                [self dismissSemiModalView];
                [self.delegate.navigationController pushViewController:commmitVC animated:YES];
            }];
        }
		if (self.type == 2 ) {
			NSDictionary *itemdic = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId],
									  @"quantity":self.quantity.text,
									  @"sku":[self.skus[self.skuIndex] valueForKey:@"name"]
									  };
			NSArray *arr = @[itemdic];
			NSDictionary *param = @{
									@"items":arr,
									@"is_ecbuy":@"1",
									};
			
			[[NetworkTool sharedTool] requestWithName:@"开启拼单" URLString:APIMallsOrders parameters:param method:@"POST" callBack:^(id responseObject) {
				
				MallCommitOrdersViewController *commmitVC = [[MallCommitOrdersViewController alloc] init];
				//        commmitVC.order = responseObject[@"data"][0];
				
				commmitVC.orderData = responseObject[@"data"];
				NSLog(@"delegate is %@, nav is %@", self.delegate, self.delegate.navigationController);
				[self dismissSemiModalView];
				[self.delegate.navigationController pushViewController:commmitVC animated:YES];
			}];
		}
		if (self.type == 3 ) {
			NSDictionary *itemdic = @{@"goods_id":[NSString stringWithFormat:@"%ld", self.goodId],
									  @"quantity":self.quantity.text,
									  @"sku":[self.skus[self.skuIndex] valueForKey:@"name"]
									  };
			NSArray *arr = @[itemdic];
			NSDictionary *param = @{
									@"items":arr,
									@"is_ecbuy":@"1",
									@"ecbuy_id":self.ecbuy_id
									};
			
			[[NetworkTool sharedTool] requestWithName:@"加入拼单" URLString:APIMallsOrders parameters:param method:@"POST" callBack:^(id responseObject) {
				
				MallCommitOrdersViewController *commmitVC = [[MallCommitOrdersViewController alloc] init];
				
				commmitVC.orderData = responseObject[@"data"];
				NSLog(@"delegate is %@, nav is %@", self.delegate, self.delegate.navigationController);
				[self dismissSemiModalView];
				[self.delegate.navigationController pushViewController:commmitVC animated:YES];
			}];
		}
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该商品暂时没货" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
	
}
- (IBAction)close:(id)sender {
	[self dismissSemiModalView];
}
- (IBAction)reduceClick:(id)sender {
    NSInteger valueOld = [self.quantity.text integerValue];
    if (valueOld > 1) {
        self.quantity.text = [NSString stringWithFormat:@"%ld", valueOld-1];
    }
}
- (IBAction)plusClick:(id)sender {
    NSInteger valueOld = [self.quantity.text integerValue];
    if (valueOld < [[self.skus[0] valueForKey:@"stock"] integerValue]) {
        self.quantity.text = [NSString stringWithFormat:@"%ld", valueOld+1];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
